﻿using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using System.IO;
namespace VNPT.Utility
{
    
    public static class StringExtensions
    {
        public static DateTime ToDateTime(this string s, string DinhDang="dd/MM/yyyy HH:mm:ss")
        {
            DateTime MyDateTime;
            MyDateTime = new DateTime();
            MyDateTime = DateTime.ParseExact(s, DinhDang, null);
            return MyDateTime;
        }

        #region StripNonAphaNumeric
        public static string StripNonAphaNumeric(this string s)
        {
            return Regex.Replace(s, "[^A-Za-z0-9]", " ").Replace("  ", " ");
        }
        public static string StripAllNonAphaNumeric(this string s)
        {
            return Regex.Replace(s, "[^A-Za-z0-9]", "").Replace("  ", "");
        }
        #endregion
        #region Flatten
        public static string Flatten(this string s)
        {
            return s.ToLower().Replace(" ", "");
        }
        #endregion
        #region FormatDateTime
        public static string FormatDateTime(this string dateString, string format)
        {
            DateTime date;
            return DateTime.TryParse(dateString, out date) ? date.ToString(format) : string.Empty;
        }
        #endregion
        #region FormatDateTimeOrdinal
        public static string FormatDateTimeOrdinal(this string dateString, string format)
        {
            if (string.IsNullOrEmpty(dateString)) { return string.Empty; }
            DateTime d = DateTime.Parse(dateString);
            string newFormat = format.Replace("d", "d$$$$$");
            string formatedDate = dateString.FormatDateTime(newFormat);
            return formatedDate.Replace("$$$$$", GetOrdinal(d.Day));
        }
        #endregion

        public static int GetMonthNumberFromName(this string s)
        {
            DateTime date;
            // note "M " is intentional due to some strange thing in c#
            bool success = DateTime.TryParseExact(s, new string[] { "MMMM", "MMM", "MM", "M " }, CultureInfo.CurrentCulture, DateTimeStyles.AllowInnerWhite, out date);
            if (success)
            {
                return date.Month;
            }
            return -1;
        }

        public static int GetDayNumberFromString(this string s)
        {
            DateTime date;
            // note "D " is intentional due to some strange thing in c#
            bool success = DateTime.TryParseExact(s, new string[] { "dd", "d " }, CultureInfo.CurrentCulture, DateTimeStyles.AllowInnerWhite, out date);
            if (success)
            {
                return date.Day;
            }
            return -1;
        }
        #region GetOrdinal

        public static string GetOrdinal(int number)
        {
            switch (number % 100)
            {
                case 11:
                case 12:
                case 13:
                    return "th";
            }
            switch (number % 10)
            {
                case 1:
                    return "st";
                case 2:
                    return "nd";
                case 3:
                    return "rd";
                default:
                    return "th";
            }
        }
        #endregion
        #region StripHtml
        public static string StripHtml(this string s)
        {
            //Replace all nastiness with space the remove double spaces
            return Regex.Replace(s, @"<(.|\n)*?>", " ").Replace(Environment.NewLine, " ").Replace("\n", " ").Replace("  ", " ");
        }
        #endregion
        #region GetSummary
        public static string GetSummary(this string s, int maxCharacters)
        {
            if (s.Length > maxCharacters + 1)
            {
                var endIndex = s.Substring(0, maxCharacters + 1).LastIndexOf(" ");
                // take care of case where string is small
                if (endIndex == -1)
                {
                    return s.Substring(0, maxCharacters) + "...";
                }
                return s.Substring(0, endIndex) + "...";
            }
            return s;
        }
        #endregion
        #region GetUrl
        public static string GetUrl(this string url, string suffix)
        {
            if (string.IsNullOrEmpty(url))
                return string.Empty;
            var s = Path.GetDirectoryName(url).Replace("\\", "/") + "/" + Path.GetFileNameWithoutExtension(url) + suffix + Path.GetExtension(url);
            if (url.StartsWith("http://"))
            {
                return s.Replace("http:/", "http://");
            }
            return s;
        }
        #endregion
        public static string ReplaceQueryStringItem(this string url, string key, string value)
        {
            if (!url.Contains("?"))
            {
                return string.Format("{0}?{1}={2}", url, key, value);
            }
            if (!url.Contains(key + "="))
            {
                return string.Format("{0}&{1}={2}", url, key, value);
            }
            return Regex.Replace(url, @"([?&]" + key + ")=[^?&]+", "$1=" + value);
        }
        public static byte ToUpperByte(this int value)
        {
            return (byte)(value & 0xff);
        }
        public static byte ToLowerByte(this int value)
        {
            return (byte)(value >> 8);
        }
        public static byte[] Copy(this byte[] sourceBuffer, int sourceStartIndex, int length)
        {
            // Construct a temp byte array and copy bytes from the sourceBuffer to the specified length. 
            byte[] temp = new byte[length];
            Array.Copy(sourceBuffer, sourceStartIndex, temp, 0, length);
            return temp;
        }
        public static UInt32 ToUInt32(this byte[] buffer, int startIndex)
        {
            UInt32 result = 0;
            for (int i = 0; i < 4; i++)
            {
                result += (UInt32)(1 << i * 8) * (UInt32)buffer[startIndex++];
            }
            return result;
        }
        public static Int32 ToInt32(this byte[] buffer, int startIndex)
        {
            return (Int32)buffer.ToUInt32(startIndex);
        }
        public static UInt16 ToUInt16(this byte[] buffer, int startIndex)
        {
            if (startIndex > buffer.Length - 1)
            {
                throw new ArgumentOutOfRangeException("startIndex", "The startIndex cannot be greater than buffer.Length - 1.");
            }
            return (UInt16)(buffer[startIndex] + 0x100 * buffer[startIndex + 1]);
        }
        public static Int16 ToInt16(this byte[] buffer, int startIndex)
        {
            return (Int16)buffer.ToUInt16(startIndex);
        }
        public static byte[] ToAsciiBytes(this string value)
        {
            return Encoding.ASCII.GetBytes(value);
        }
        public static string ToAsciiString(this byte[] buffer, int startIndex)
        {
            // Converts the byte array to string using ASCII encoding and removes all trailing zeroes.
            return Encoding.ASCII.GetString(buffer, startIndex, buffer.Length - startIndex).TrimEnd('\0');
        }
        public static string ToAsciiString(this byte[] buffer, int startIndex, int length)
        {
            // Construct a temp array.
            byte[] data = new byte[length];
            Array.Copy(buffer, startIndex, data, 0, length);
            return data.ToAsciiString(0);
        }
        public static string ToHexString(this byte[] value)
        {
            string result = BitConverter.ToString(value);
            return result;
        }

        #region Hàm cắt chuổi


        public static string Left(this string param, int length)
        {
            string result = "";
            if (param.Length > 0)
            {
                if (length > param.Length)
                {
                    length = param.Length;
                }
                result = param.Substring(0, length);
            }
            return result;
        }
        public static string Right(this string param, int length)
        {
            string result = "";
            if (param.Length > 0)
            {
                if (length > param.Length)
                {
                    length = param.Length;
                }
                result = param.Substring(param.Length - length, length);
            }
            return result;
        }

        public static string Mid(this string param, int start, int length)
        {
            string result = "";
            if ((param.Length > 0) && (start < param.Length))
            {
                if (start + length > param.Length)
                {
                    length = param.Length - start;
                }

                result = param.Substring(start, length);
            }
            return result;
        }

        public static string Mid(this string param, int startIndex)
        {
            string result = param.Substring(startIndex);
            return result;
        }
        #endregion
    }
}
